package com.fss.util;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class BaseHqlDao extends HibernateDaoSupport {

	protected int executeUpdate(final String hql, final Object values[])
			throws DataAccessException {
		Object objRet = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) {
				Query query = session.createQuery(hql);
				if (null != values) {
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
				return new Integer(query.executeUpdate());
			}
		});
		return ((Integer) objRet).intValue();
	}

	
	protected boolean isDuplicated(final String hql, final Object[] values) {
		Object count = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) {
				Query query = session.createQuery(hql);
				if (null != values) {
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
				return query.uniqueResult();
			}
		});
		return (((Long) count).longValue() > 0);
	}
	
	/*protected String getMaxId(String className,String value) {
		final String hql = "select max(id) from " + className;
		Object id = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				return query.uniqueResult();
			}
		});

		return (null == id ? "" : (String) id);
	}*/
	
	protected String getMaxId(String hql,Object[] value) {
		String queryString = "select max(id) "+ hql; 
        List tmpList = getHibernateTemplate().find(queryString, value);
        Object id=tmpList.get(0);
        return (null == id ? "" : (String) id);
	}

	protected boolean isExist(String hql, Object[] value) {
		List tmpList = getHibernateTemplate().find(hql, value);
		if (null == tmpList || tmpList.size() < 1) {
			return false;
		} else {
			return true;
		}
	}
}